import axios from "axios";
import { ref } from "vue";
import { ElMessage } from "element-plus";

const PLACE_URL = "https://restapi.amap.com/v3/place/text";

export interface RemoteOption {
  value: string; // 名称（给 el-select 显示）
  label: string; // 名称+地址组合
  raw: any; // 完整 poi 对象，后续用
}

/** 远程搜索函数（直接作为 el-select 的 remote-method） */
export function useRemotePlace(key: string) {
  const loadDataing = ref(false);
  const options = ref<RemoteOption[]>([]);

  async function remoteMethod(query: string) {
    if (!query) {
      options.value = [];
      return;
    }
    loadDataing.value = true;
    try {
      const { data } = await axios.get(PLACE_URL, {
        params: {
          key,
          keywords: query,
          city: "全国",
          offset: 20,
          page: 1,
          output: "JSON",
        },
      });
      if (data.status === "1" && data.pois) {
        console.log("搜索结果:454545445454445545", data.pois);
        options.value = data.pois.map((p: any) => ({
          value: p.name, // 名称
          label: `${p.pname} ${p.cityname} ${p.adname} ${p.name} | ${p.address}`, // 下拉里给用户看
          raw: p, // 完整数据备用
        }));
      } else {
        options.value = [];
      }
    } catch (e) {
      ElMessage.error("网络错误");
      options.value = [];
    } finally {
      loadDataing.value = false;
    }
  }

  return { loadDataing, options, remoteMethod };
}

/** 选中后解析详细字段（经纬度+adcode） */
export function parsePoi(item: RemoteOption) {
  const p = item.raw;
  const [lng, lat] = p.location.split(",").map(Number);
  return {
    address: p.address + p.name,
    name: p.name,
    lng,
    lat,
    adcode: p.adcode,
  };
}
